package com.hly.tool.http;

import com.matrixone.apps.framework.ui.UIUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

/**
 * @Auther: Jack.Hao
 * @Date: 2021/4/13 11:36
 * @Description:
 */
public class http
{
    private static final String CONTENT_TYPE_TEXT_JSON = "text/json";

    private static RequestConfig defaultConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();

    /**
     * 上传文件
     *
     * @param url
     * @param file
     * @return
     */
    public static String doPostFile(String url, File file) throws IOException
    {
        String result = "";
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpResponse httpResponse = null;
//        HttpPost httpPost = new HttpPost("http://localhost:8080/WEY.WebApp/auth/right/right/receiveFile.html");
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(defaultConfig);
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
        //multipartEntityBuilder.setCharset(Charset.forName("UTF-8"));
        //File file = new File("F:\\Ken\\1.PNG");
        //FileBody bin = new FileBody(file);
//        File file = new File("F:\\Ken\\abc.pdf");
        //multipartEntityBuilder.addBinaryBody("file", file,ContentType.create("image/png"),"abc.pdf");
        //当设置了setSocketTimeout参数后，以下代码上传PDF不能成功，将setSocketTimeout参数去掉后此可以上传成功。上传图片则没有个限制
        //multipartEntityBuilder.addBinaryBody("file",file,ContentType.create("application/octet-stream"),"abd.pdf");
        multipartEntityBuilder.addBinaryBody("files", file);
        //multipartEntityBuilder.addPart("comment", new StringBody("This is comment", ContentType.TEXT_PLAIN));
        multipartEntityBuilder.addTextBody("comment", "this is comment");
        HttpEntity httpEntity = multipartEntityBuilder.build();
        httpPost.setEntity(httpEntity);

        httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode == 200)
        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
            StringBuffer buffer = new StringBuffer();
            String str = "";
            while (!StringUtils.isEmpty(str = reader.readLine()))
            {
                buffer.append(str);
            }
            result = buffer.toString();
//            System.out.println("result = "+result);
        }

        httpClient.close();
        if (httpResponse != null)
        {
            httpResponse.close();
        }

        return result;
    }


    /**
     * httpclient 发送 get  请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String doGet(String url, HttpParams params) throws Exception
    {
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        httpClient = new SSLClient();
        httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpGet.setConfig(defaultConfig);
        httpGet.setParams(params);

        HttpResponse response = httpClient.execute(httpGet);
        if (response != null)
        {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null)
            {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
        return result;
    }


    /**
     * httpclient 发送 get  请求
     *
     * @param url      请求地址
     * @param paramMap 请求参数
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map paramMap) throws Exception
    {
        //请求体
        HttpParams params = new BasicHttpParams();

        //添加请求参数
        if (paramMap != null && !paramMap.isEmpty())
        {
            Iterator iterator = paramMap.keySet().iterator();
            while (iterator.hasNext())
            {
                String key = (String) iterator.next();
                String value = (String) paramMap.get(key);
                params.setParameter(key, value);
            }
        }


        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;
        httpClient = new SSLClient();
        httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
        httpGet.setConfig(defaultConfig);
        httpGet.setParams(params);


        HttpResponse response = httpClient.execute(httpGet);
        if (response != null)
        {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null)
            {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }
        return result;
    }

    /**
     * httpclient 发送 get  请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String doGet(String url, HttpParams params, Map herderMap) throws Exception
    {
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;

        httpClient = new SSLClient();
        httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (herderMap != null && !herderMap.isEmpty())
        {
            Set keySet = herderMap.keySet();
            Iterator iterator = keySet.iterator();
            while (iterator.hasNext())
            {
                String key = (String) iterator.next();
                String value = "";
                String type = (String) herderMap.get("type");
                if (type == null || type.isEmpty() || type.toUpperCase().trim().equals("string"))
                {
                    value = (String) herderMap.get(key);
                }
                else if (type.equals("list"))
                {
                    List<String> heards = (List<String>) herderMap.get(key);
                    value = heards.toString();
                }
                httpGet.setHeader(key, value);
            }
        }
        httpGet.setConfig(defaultConfig);
        httpGet.setParams(params);
        HttpResponse response = httpClient.execute(httpGet);
        if (response != null)
        {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null)
            {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }

        return result;
    }

    /**
     * httpclient 发送 get  请求
     *
     * @param url       地址
     * @param paramMap  请求参数
     * @param herderMap
     * @return
     * @throws Exception
     */
    public static String doGet(String url, Map paramMap, Map herderMap) throws Exception
    {
        HttpClient httpClient = null;
        HttpGet httpGet = null;
        String result = null;

        httpClient = new SSLClient();
        httpGet = new HttpGet(url);
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");

        //添加头部信息
        if (herderMap != null && !herderMap.isEmpty())
        {
            Set keySet = herderMap.keySet();
            Iterator iterator = keySet.iterator();
            while (iterator.hasNext())
            {
                String key = (String) iterator.next();
                String value = "";
                String type = (String) herderMap.get("type");
                if (type == null || type.isEmpty() || type.toUpperCase().trim().equals("string"))
                {
                    value = (String) herderMap.get(key);
                }
                else if (type.equals("list"))
                {
                    List<String> heards = (List<String>) herderMap.get(key);
                    value = heards.toString();
                }
                httpGet.setHeader(key, value);
            }
        }


        //请求体
        HttpParams params = new BasicHttpParams();

        //添加请求参数
        if (paramMap != null && !paramMap.isEmpty())
        {
            Iterator iterator = paramMap.keySet().iterator();
            while (iterator.hasNext())
            {
                String key = (String) iterator.next();
                String value = (String) paramMap.get(key);
                params.setParameter(key, value);
            }
        }


        httpGet.setConfig(defaultConfig);
        httpGet.setParams(params);
        HttpResponse response = httpClient.execute(httpGet);
        if (response != null)
        {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null)
            {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }

        return result;
    }


    /**
     * 发送 post请求
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params) throws Exception
    {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;

        httpClient = new SSLClient();
        httpPost = new HttpPost(url);
//            String js = "{\"type\":\"VPMReference\",\"name\":\"706923\",\"randomChar\":\"706923\"}";
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity se = new StringEntity(params, Charset.forName("UTF-8"));
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null)
        {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null)
            {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }

        return result;
    }

    /**
     * 发送 post请求
     *
     * @param url
     * @param params
     * @return
     */
    public static Map postDownFile(String url, String params) throws Exception
    {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        Map result = new HashMap();

        httpClient = new SSLClient();
        httpPost = new HttpPost(url);
//            String js = "{\"type\":\"VPMReference\",\"name\":\"706923\",\"randomChar\":\"706923\"}";
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        StringEntity se = new StringEntity(params, Charset.forName("UTF-8"));
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);

        String filelength = "";
        String filename = "";
        InputStream inputStream = null;


        Header[] filelengths = response.getHeaders("Content-Length");
        if (filelengths != null && filelengths.length > 0)
        {
            filelength = filelengths[0].getValue();
            if (UIUtil.isNullOrEmpty(filelength))
            {
                filelength = "0";
            }
        }

        Header[] filenames = response.getHeaders("filename");
        if (filenames != null && filenames.length > 0)
        {
            filename = filenames[0].getValue();
            if (UIUtil.isNullOrEmpty(filename))
            {
                filename = "";
            }
        }
        if (response != null)
        {
            inputStream = response.getEntity().getContent();
        }

//        String filelength = "";
//        String filename = "";
//        InputStream inputStream = null;

        result.put("filelength",filelength);
        result.put("filename",filename);
        result.put("inputStream",inputStream);

        return result;
    }


    /**
     * @param url
     * @param params
     * @return
     */
    public static String doPost(String url, String params, Map herderMap) throws Exception
    {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;

        httpClient = new SSLClient();
        httpPost = new HttpPost(url);
//            String js = "{\"type\":\"VPMReference\",\"name\":\"706923\",\"randomChar\":\"706923\"}";
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (herderMap != null && !herderMap.isEmpty())
        {
            Set keySet = herderMap.keySet();
            Iterator iterator = keySet.iterator();
            while (iterator.hasNext())
            {
                String key = (String) iterator.next();
                String value = "";
                String type = (String) herderMap.get("type");
                if (type == null || type.isEmpty() || type.toUpperCase().trim().equals("string"))
                {
                    value = (String) herderMap.get(key);
                }
                else if (type.equals("list"))
                {
                    List<String> heards = (List<String>) herderMap.get(key);
                    value = heards.toString();
                }
                httpPost.setHeader(key, value);
            }
        }
        StringEntity se = new StringEntity(params, Charset.forName("UTF-8"));
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null)
        {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null)
            {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }

        return result;
    }


    /**
     * @param url
     * @param params
     * @return
     */
    public static String Post(String url, String params, Map herderMap) throws Exception
    {
        HttpClient httpClient = null;
        HttpPost httpPost = null;
        String result = null;

        httpClient = new SSLClient();
        httpPost = new HttpPost(url);
//            String js = "{\"type\":\"VPMReference\",\"name\":\"706923\",\"randomChar\":\"706923\"}";
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        if (herderMap != null && !herderMap.isEmpty())
        {
            Set keySet = herderMap.keySet();
            Iterator iterator = keySet.iterator();
            while (iterator.hasNext())
            {
                String key = (String) iterator.next();
                String value = "";
                String type = (String) herderMap.get("type");
                if (type == null || type.isEmpty() || type.toUpperCase().trim().equals("string"))
                {
                    value = (String) herderMap.get(key);
                }
                else if (type.equals("list"))
                {
                    List<String> heards = (List<String>) herderMap.get(key);
                    value = heards.toString();
                }
                httpPost.setHeader(key, value);
            }
        }
        StringEntity se = new StringEntity(params, Charset.forName("UTF-8"));
        se.setContentType(CONTENT_TYPE_TEXT_JSON);
        httpPost.setEntity(se);
        HttpResponse response = httpClient.execute(httpPost);
        if (response != null)
        {
            HttpEntity resEntity = response.getEntity();
            if (resEntity != null)
            {
                result = EntityUtils.toString(resEntity, "UTF-8");
            }
        }

        return result;
    }


    public static void main(String[] args) throws Exception
    {

        String url = "http://localhost:8084/testfile";

        doPostFile(url, new File("D:\\FTP\\userBehavior\\ToTC\\SFDPKG_prd-40535902-00004476A1.zip"));

    }

}
